<?php

namespace app\api\controller;

use app\api\model\Category as ModelCategory;
use think\facade\Db;

class Category
{
    public function index()
    {
        $pid = input('pid', 0);
        if ($pid == 0) {
            // 查询一级分类
            $list = ModelCategory::where(['status' => 1, 'pid' => 0])
                ->order('sort desc')
                ->select();

            // 遍历一级分类
            foreach ($list as $k => $v) {
                // 获取当前一级分类下的所有二级分类ID
                $subCateIds = ModelCategory::where(['status' => 1, 'pid' => $v['id']])
                    ->column('id');

                if (empty($subCateIds)) {
                    $list[$k]['total'] = 0;
                    $list[$k]['today'] = 0;
                    continue;
                }

                // 统计所有二级分类下的文章总数（已审核）
                $totalArticles = Db::name('article')
                    ->where([
                        ['cate_id', 'in', $subCateIds],
                        ['status', '=', 1],
                        ['delete_time', '=', 0]

                    ])
                    ->count();

                // 统计所有二级分类下今日发布的文章数量（已审核）
                $todayArticles = Db::name('article')
                    ->where([
                        ['cate_id', 'in', $subCateIds],
                        ['status', '=', 1],
                        ['create_time', '>=', strtotime(date('Y-m-d 00:00:00'))],
                        ['delete_time', '=', 0]
                    ])
                    ->count();

                // 将统计结果添加到分类数据中
                $list[$k]['total'] = $totalArticles;
                $list[$k]['today'] = $todayArticles;
            }
        } else {
            // 得到父分类所有子分类
            $list = ModelCategory::where(['status' => 1, 'pid' => $pid])
                ->order('sort desc')
                ->select();
        }

        return success($list);
    }
    //    收藏的分类
    public function force() {}
}
